<?php
if (!function_exists("p")) {
    function p($data)
    {
        echo '<pre>';
        print_r($data);die;
    }
}

if (!function_exists("current_is")) {
    /**
     * 判断路由
     * @return bool
     */
    function current_is($name)
    {
        $is = false;
        $route = \Illuminate\Support\Facades\Route::current();
        if ($route->getName() == $name) {
            $is = true;
        }
        return $is;
    }
}


if (!function_exists("cdn")) {
    /**
     * 拼接云储存的地址q
     */
    function cdn($name, $prot = '')
    {
        $domain = config('filesystems.disks.qiniu.domains.https');
        $protocol = !empty($prot) ? $prot : config('filesystems.disks.qiniu.protocol');
        $url = sprintf("%s://%s/%s", $protocol, $domain, $name);
        return $url;
    }
}


if (!function_exists("bloginfo")) {
    /**
     * 读取动态配置
     */
    function bloginfo($name, $clear = false)
    {
        $options = cache('options');
        if (empty($options) || $clear) {
            cache()->forget('options');
            $expiresAt = \Carbon\Carbon::now()->addMinutes(1440);
            $optionsList = \Models\Options::orderBy('id')->select('option_name', 'option_value')->get()->toArray();
            foreach ($optionsList as $key => $option) {
                $options[strtolower($option['option_name'])] = $option['option_value'];
            }
            cache(['options' => $options], $expiresAt);
        }
        return isset($options[$name]) ? $options[$name] : '';
    }
}


if (!function_exists('msubstr')) {
    /**
     * 字符串截取
     */
    function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
    {
        if (function_exists("mb_substr")) {
            $slice = mb_substr($str, $start, $length, $charset);
        } elseif (function_exists('iconv_substr')) {
            $slice = iconv_substr($str, $start, $length, $charset);
            if (false === $slice) {
                $slice = '';
            }
        } else {
            $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("", array_slice($match[0], $start, $length));
        }
        return $suffix ? $slice . '...' : $slice;

    }
}


if (!function_exists("get_description")) {
    /**
     * 根据文章ID截取描述
     * @param $id
     * @param int $word
     * @return string
     * @author Mr.Cong <i@cong5.net>
     */
    function get_description($content, $word = 210)
    {
        if (empty($content)) {
            return '...';
        }
        $description = msubstr(strip_tags($content), 0, $word);
        return $description;
    }
}

//生成订单号
if( ! function_exists('create_sn') ) {

    function create_sn()
    {
        mt_srand((double )microtime() * 1000000);
        return date("YmdHis") . str_pad(mt_rand(1, 99999), 5, "0", STR_PAD_LEFT);
    }
}
//安全过滤函数
if( ! function_exists('safe_replace') ) {

    function safe_replace($string)
    {
        $string = str_replace('%20', '', $string);
        $string = str_replace('%27', '', $string);
        $string = str_replace('%2527', '', $string);
        $string = str_replace('*', '', $string);
        $string = str_replace('"', '&quot;', $string);
        $string = str_replace("'", '', $string);
        $string = str_replace('"', '', $string);
        $string = str_replace(';', '', $string);
        $string = str_replace('<', '&lt;', $string);
        $string = str_replace('>', '&gt;', $string);
        $string = str_replace("{", '', $string);
        $string = str_replace('}', '', $string);
        $string = str_replace('\\', '', $string);
        return $string;
    }
}
if( ! function_exists('password') ) {

    function password($password, $encrypt = '')
    {
        $pwd = array();
        $pwd['encrypt'] = $encrypt ? $encrypt : create_randomstr();
        $pwd['password'] = md5(md5(trim($password)) . $pwd['encrypt']);
        return $encrypt ? $pwd['password'] : $pwd;
    }
}
//生成随机字符串
if( ! function_exists('create_randomstr') ) {

    function create_randomstr($lenth = 6)
    {
        return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
    }
}
//产生随机字符串
if( ! function_exists('random') ) {

    function random($length, $chars = '0123456789')
    {
        $hash = '';
        $max = strlen($chars) - 1;
        mt_rand();
        for ($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }
}

if( ! function_exists('is_username') ) {

    function is_username($username)
    {
        $strlen = strlen($username);
        if (!preg_match("/^[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/", $username)) {
            return false;
        } elseif (20 < $strlen || $strlen < 2) {
            return false;
        }
        return true;
    }
}

if( ! function_exists('is_email') ) {

    function is_email($email)
    {
        return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
    }
}
//获取请求ip
if( ! function_exists('ip') ) {

    function ip()
    {
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '';
    }
}

if( ! function_exists('http_request')  ){
    function http_request($url,$data = null,$headers=array())
    {
        $curl = curl_init();
        if( count($headers) >= 1 ){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_URL, $url);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}

//curl封装函数
if( ! function_exists('a_curl')  ) {
    function a_curl($url, $params, $method = 'GET', $header = array(), $multi = false)
    {

        $opts = array(
            CURLOPT_TIMEOUT => 60,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => $header
        );
        /* 根据请求类型设置特定参数 */
        switch (strtoupper($method)) {
            case 'GET':
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                break;
            case 'POST':
                //判断是否传输文件
//                $params = $multi ? $params : http_build_query($params);

                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                return 0;
        }

        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $error = curl_error($ch);


        curl_close($ch);
        return json_decode($data, true);
    }
}


//删除空格
if( ! function_exists('trimall')  ){
    function trimall($str)//删除空格
    {
        $oldchar=array(" ","　","\t","\n","\r");

        $newchar=array("","","","","");
        return str_replace($oldchar,$newchar,$str);
    }
}


//将时间字符串格式的处理成为年月日的格式
if( ! function_exists('timestampToDate') ){
    function timestampToDate($timestamp,$dateFormat='Y-m-d',$default=null){
        if( empty($timestamp)  ){
            return $default;
        }
        $times = strtotime($timestamp);
        if( empty($times) ){
            return $default;
        }
        return date($dateFormat,$times);
    }
}


//设置头部信息
if( !function_exists('setHeaderContentType') ){
    function setHeaderContentType($type='',$char='utf-8'){
        switch (trim($type)) {
            case 'javascript':
                header("Content-Type:application/x-javascript;charset={$char}");
                break;
            case 'json':
                header("Content-Type:application/json;charset={$char}");
                break;
            case 'xml':
                header("Content-type: text/xml;charset={$char}");
                break;
            case 'swf':
                header("Content-type: application/x-shockwave-flash;");
                break;
            case 'gif':
                header("Content-type:image/gif;");
                break;
            case 'jpg':
                header("Content-type:image/jpg;");
                break;
            case 'png':
                header("Content-type:image/png;");
                break;
            case 'css':
                header("Content-type: text/css;charset={$char}");
                break;
            default:
                header("Content-type: text/html;charset={$char}");
        }
    }
}

//检验手机是否合法
function is_phone($phone){
    if( empty($phone) ){
        return false;
    }
    return preg_match("/^1[0-9]{10}$/", $phone) ? true : false;
}


// 二维数组排序
function array_orderby(){
    $args = func_get_args();
    $data = array_shift($args);
    foreach ($args as $n => $field) {
        if (is_string($field)) {
            $tmp = array();
            foreach ($data as $key => $row)
                $tmp[$key] = $row[$field];
            $args[$n] = $tmp;
        }
    }
    $args[] = &$data;
    call_user_func_array('array_multisort', $args);
    return array_pop($args);
}

//手机号格式化 中间4位用 * 代替
if( ! function_exists('phoneFormatHiden') ){

    function phoneFormatHiden($phone){
        //遍历处理手机号
        $xing = substr($phone,3,4);
        $a = str_replace($xing,'****',$phone);
        return $a;
    }
}
//xml 转数组
if( ! function_exists('xmlToArray') ) {
    function xmlToArray($xml)
    {
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $data;
    }
}

// 计算，开标时间
if( ! function_exists('bidStartTime') ) {
    function bidStartTime()
    {
        //早上10点以前，明天 早上10开始， 10点以后，后天10点
        //今天早上时间
        $day10= date("Y-m-d H:i:s",strtotime(date("Y-m-d"))+3600*10);
        //明天早上10点
        $ming10= date("Y-m-d H:i:s",strtotime(date("Y-m-d",strtotime('+1 day')))+3600*10);

        //后天早上10点
        $hou10= date("Y-m-d H:i:s",strtotime(date("Y-m-d",strtotime('+2 day')))+3600*10);
        //明天
        $now = now();
        if($now <$day10){
            return $ming10;
        }else{
            return $hou10;
        }

    }
}
//公司名称过滤
if( ! function_exists('companyNameFilter') ) {
    function companyNameFilter($data)
    {
//        $area  = DB::table('area')->whereIn('level',[1])
//            ->pluck('short_name')->toArray();
//        $frontArr = implode('',$area);
        $frontArr = '北京天津河北山西内蒙古辽宁吉林黑龙江上海江苏浙江安徽福建江西山东河南湖北湖南广东广西海南重庆四川贵州云南西藏陕西甘肃青海宁夏新疆台湾香港澳门';
        $endArr = '诊所门诊部医院卫生院服务中心站防疫血站检验中心卫生室医疗机构公司';

        $len =  mb_strlen($data);
        //如果小于4位直接隐藏
        if($len < 5){
            return '********';
        }
        $front = mb_substr($data,0,2);
        $end = mb_substr($data,-2);


        if(mb_strpos($frontArr,$front) === false){
            $front = '**';
        }
        if(mb_strpos($endArr,$end) === false){
            $end='**';
        }


        return $front.'****'.$end;

    }
}
//生成邀请码
if( ! function_exists('makeInviteCode') ) {

    function makeInviteCode($j = 8)
    {
        $string = "";
        for ($i = 0; $i < $j; $i++) {
            srand((double)microtime() * 1234567);
            $x = mt_rand(0, 2);
            switch ($x) {
                case 0:
                    $string .= chr(mt_rand(97, 122));
                    break;
                case 1:
                    $string .= chr(mt_rand(65, 90));
                    break;
                case 2:
                    $string .= chr(mt_rand(48, 57));
                    break;
            }
        }
        return strtoupper($string); //to uppercase
    }
}

// 写入日志
if( ! function_exists('writeLog') ) {
    function writeLog($logData, $logPath, $filename = '', $mode = 'a+', $chmod = 0777)
    {
        /* 	$storagePathArr = [
                'logs',
                'errorLog',
                trim($logPath,'/'),
                date('Y-m-d').'.log'
            ]; */

        if ($filename == '') {
            $path = "logs/errorLog/{$logPath}/" . date('Y-m-d') . '.log';
        } else {

            $path = "logs/errorLog/{$logPath}/" . $filename . '.log';
        }

        $storagePath = $path;
        $logPath = storage_path($storagePath);//存储路径保存如：storage/logs/errorLog/{$logPath}/2016-07-21.log
        $logDir = dirname($logPath);
        if (!is_dir($logDir)) {
            mkdir($logDir, $chmod, true);
        }
        if (!file_exists($logPath)) {
            touch($logPath);
            chmod($logPath, $chmod);
        }
        $f = fopen($logPath, 'a+');
        $date = date('Y-m-d H:i:s');
        $logStr = is_array($logData) ? print_r($logData, true) : $logData;
        fwrite($f, $date . ' => ' . $logStr . PHP_EOL);
        fclose($f);
    }
}